#include "state_machine/v1/state_machine.h"

StateMachine::StateMachine() : current_state(State::AT_HOME)
{
    setupTransitions();

    // 查找初始状态的特殊条目
    for (const auto& t : transitions)
    {
        if (t.current == current_state && !static_cast<bool>(t.event) && t.enter_action)
        {
            t.enter_action();
            break;
        }
    }
}

void StateMachine::setupTransitions()
{
    transitions = {// 在家状态的转移
                   {State::AT_HOME, Event::SUNNY, State::OUTSIDE,
                    []() { std::cout << "[状态] 离开在家状态 "; },
                    []() { std::cout << "[状态] 进入外出状态 [动作] 出门散步！\n"; }},
                   // 外出状态的转移
                   {State::OUTSIDE, Event::RAINING, State::AT_HOME,
                    []() { std::cout << "[状态] 离开外出状态 "; },
                    []() { std::cout << "[状态] 进入在家状态 [动作] 躺平追剧！\n"; }},
                   // 专门为初始状态添加的条目（无事件触发）
                   {State::AT_HOME, Event{},  // 空事件表示初始状态
                    State::AT_HOME,
                    nullptr,  // 无转移动作
                    []() { std::cout << "[初始状态] 进入在家状态 [动作] 躺平追剧！\n"; }}};
}

void StateMachine::handleEvent(Event event)
{
    std::cout << "[事件] " << (event == Event::RAINING ? "开始下雨" : "天气转晴") << "\n";

    for (const auto& t : transitions)
    {
        if (t.current == current_state && t.event == event)
        {
            // 执行转移动作
            if (t.transition_action)
            {
                t.transition_action();
            }

            // 更新状态
            current_state = t.next;

            // 执行新状态的enter动作
            if (t.enter_action)
            {
                t.enter_action();
            }

            return;
        }
    }

    std::cout << "[状态] 无状态变化\n";
}

State StateMachine::getCurrentState() const { return current_state; }

void testStateMachine()
{
    StateMachine sm;

    // 晴天事件
    std::cout << "=== 处理晴天事件 ===\n";
    sm.handleEvent(Event::SUNNY);

    // 下雨事件
    std::cout << "=== 处理下雨事件 ===\n";
    sm.handleEvent(Event::RAINING);
}